<?php
/**
 * 用户管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理用户操作
$success = '';
$error = '';

// 处理删除用户请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $user_id = (int)$_GET['delete'];
    
    // 不允许删除自己的账号
    if ($user_id == $_SESSION['user_id']) {
        $error = '不能删除当前登录的账号';
    } else {
        // 开始事务
        $conn->begin_transaction();
        
        try {
            // 检查用户是否存在
            $sql = "SELECT role FROM users WHERE id = $user_id";
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $user = $result->fetch_assoc();
                
                // 根据角色删除相关表中的记录
                if ($user['role'] == 'patient') {
                    $sql = "DELETE FROM patients WHERE user_id = $user_id";
                    $conn->query($sql);
                } elseif ($user['role'] == 'doctor') {
                    $sql = "DELETE FROM doctors WHERE user_id = $user_id";
                    $conn->query($sql);
                }
                
                // 删除用户的系统日志
                $sql = "DELETE FROM system_logs WHERE user_id = $user_id";
                $conn->query($sql);
                
                // 删除用户主表记录
                $sql = "DELETE FROM users WHERE id = $user_id";
                $conn->query($sql);
                
                // 记录操作日志
                logAction($_SESSION['user_id'], '删除用户（ID：' . $user_id . '）');
                
                // 提交事务
                $conn->commit();
                
                $success = '用户删除成功！';
            } else {
                $error = '用户不存在';
                $conn->rollback();
            }
        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
            $error = '删除用户失败：' . $e->getMessage();
        }
    }
}

// 处理添加/编辑用户表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_user']) || isset($_POST['edit_user'])) {
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? '';
        $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        
        // 基本验证
        if (empty($username) || empty($email) || empty($role)) {
            $error = '请填写所有必填字段';
        } else if (!isValidEmail($email)) {
            $error = '请输入有效的电子邮件地址';
        } else {
            // 检查用户名和邮箱是否已存在（编辑时排除当前用户）
            $username = $conn->real_escape_string($username);
            $email = $conn->real_escape_string($email);
            
            if (isset($_POST['add_user'])) {
                $sql = "SELECT * FROM users WHERE username = '$username' OR email = '$email'";
            } else {
                $sql = "SELECT * FROM users WHERE (username = '$username' OR email = '$email') AND id != $user_id";
            }
            
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $error = '用户名或电子邮件已被使用';
            } else {
                // 添加新用户
                if (isset($_POST['add_user'])) {
                    if (empty($password)) {
                        $error = '请输入密码';
                    } else {
                        $hashed_password = md5($password); // 生产环境应使用更安全的方法
                        $role = $conn->real_escape_string($role);
                        
                        $sql = "INSERT INTO users (username, password, email, role, created_at) 
                                VALUES ('$username', '$hashed_password', '$email', '$role', NOW())";
                        
                        if ($conn->query($sql)) {
                            $new_user_id = $conn->insert_id;
                            
                            // 记录操作日志
                            logAction($_SESSION['user_id'], '添加用户（ID：' . $new_user_id . '）');
                            
                            $success = '用户添加成功！';
                        } else {
                            $error = '添加用户失败：' . $conn->error;
                        }
                    }
                }
                // 编辑现有用户
                else {
                    $role = $conn->real_escape_string($role);
                    
                    if (empty($password)) {
                        $sql = "UPDATE users SET username = '$username', email = '$email', role = '$role' WHERE id = $user_id";
                    } else {
                        $hashed_password = md5($password); // 生产环境应使用更安全的方法
                        $sql = "UPDATE users SET username = '$username', password = '$hashed_password', email = '$email', role = '$role' WHERE id = $user_id";
                    }
                    
                    if ($conn->query($sql)) {
                        // 记录操作日志
                        logAction($_SESSION['user_id'], '更新用户（ID：' . $user_id . '）');
                        
                        $success = '用户更新成功！';
                    } else {
                        $error = '更新用户失败：' . $conn->error;
                    }
                }
            }
        }
    }
}

// 获取所有用户
$users = [];

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10; // 每页显示的记录数
$offset = ($page - 1) * $limit;

// 获取用户总数
$count_sql = "SELECT COUNT(*) as total FROM users";
$count_result = $conn->query($count_sql);
$total_records = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);

// 获取当前页的用户数据
$sql = "SELECT * FROM users ORDER BY created_at DESC LIMIT $offset, $limit";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}

// 如果是编辑请求，获取用户信息
$edit_user = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $user_id = (int)$_GET['edit'];
    $sql = "SELECT * FROM users WHERE id = $user_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_user = $result->fetch_assoc();
    }
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">用户管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addUserModal">
                            <i class="fas fa-plus mr-1"></i> 添加用户
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 用户列表 -->
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h5 class="mb-0">用户列表</h5>
                            </div>
                            <div class="col-auto">
                                <div class="input-group">
                                    <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索用户...">
                                    <div class="input-group-append">
                                        <button class="btn btn-sm btn-outline-secondary" type="button" id="searchButton">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover table-striped" id="userTable">
                                <thead>
                                    <tr>
                                        <th onclick="sortTable(0)">ID <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(1)">用户名 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(2)">邮箱 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(3)">角色 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(4)">注册时间 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(5)">最后登录 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($users)): ?>
                                        <tr>
                                            <td colspan="7" class="text-center">暂无用户</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($users as $user): ?>
                                            <tr>
                                                <td><?php echo $user['id']; ?></td>
                                                <td>
                                                    <?php echo $user['username']; ?>
                                                    <?php if ($user['id'] == $_SESSION['user_id']): ?>
                                                        <span class="badge badge-info ml-1">当前用户</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo $user['email']; ?></td>
                                                <td>
                                                    <?php
                                                    switch ($user['role']) {
                                                        case 'admin':
                                                            echo '<span class="badge badge-danger">管理员</span>';
                                                            break;
                                                        case 'doctor':
                                                            echo '<span class="badge badge-success">医生</span>';
                                                            break;
                                                        case 'patient':
                                                            echo '<span class="badge badge-info">患者</span>';
                                                            break;
                                                        default:
                                                            echo '<span class="badge badge-secondary">普通用户</span>';
                                                    }
                                                    ?>
                                                </td>
                                                <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                                                <td>
                                                    <?php echo $user['last_login'] ? date('Y-m-d H:i', strtotime($user['last_login'])) : '从未登录'; ?>
                                                </td>
                                                <td>
                                                    <a href="?edit=<?php echo $user['id']; ?>" class="btn btn-sm btn-info" title="编辑用户">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                        <a href="?delete=<?php echo $user['id']; ?>" class="btn btn-sm btn-danger" title="删除用户" onclick="return confirm('确定要删除此用户吗？此操作不可恢复！');">
                                                            <i class="fas fa-trash-alt"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <div class="row align-items-center">
                            <div class="col">
                                <small class="text-muted">共 <?php echo $total_records; ?> 个用户，当前显示第 <?php echo $page; ?> 页，共 <?php echo $total_pages; ?> 页</small>
                            </div>
                            <div class="col-auto">
                                <nav aria-label="Page navigation">
                                    <ul class="pagination pagination-sm mb-0">
                                        <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo isset($_GET['edit']) ? '&edit='.$_GET['edit'] : ''; ?>">上一页</a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
                                        <?php endif; ?>

                                        <?php
                                        // 显示分页链接
                                        $start_page = max(1, $page - 2);
                                        $end_page = min($total_pages, $page + 2);
                                        
                                        // 总是显示第一页链接
                                        if ($start_page > 1) {
                                            echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                                            if ($start_page > 2) {
                                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                            }
                                        }
                                        
                                        // 显示当前页面的前后几页
                                        for ($i = $start_page; $i <= $end_page; $i++) {
                                            if ($i == $page) {
                                                echo '<li class="page-item active"><a class="page-link" href="#">' . $i . '</a></li>';
                                            } else {
                                                echo '<li class="page-item"><a class="page-link" href="?page=' . $i . '">' . $i . '</a></li>';
                                            }
                                        }
                                        
                                        // 总是显示最后一页链接
                                        if ($end_page < $total_pages) {
                                            if ($end_page < $total_pages - 1) {
                                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                            }
                                            echo '<li class="page-item"><a class="page-link" href="?page=' . $total_pages . '">' . $total_pages . '</a></li>';
                                        }
                                        ?>

                                        <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo isset($_GET['edit']) ? '&edit='.$_GET['edit'] : ''; ?>">下一页</a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>
    
    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="addUserModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">添加用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="username">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="form-group">
                            <label for="email">电子邮箱 <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        <div class="form-group">
                            <label for="password">密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="form-group">
                            <label for="role">角色 <span class="text-danger">*</span></label>
                            <select class="form-control" id="role" name="role" required>
                                <option value="">请选择角色</option>
                                <option value="admin">管理员</option>
                                <option value="doctor">医生</option>
                                <option value="patient">患者</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="add_user" class="btn btn-primary">添加</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑用户模态框 -->
    <?php if ($edit_user): ?>
    <div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true" data-show="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="user_id" value="<?php echo $edit_user['id']; ?>">
                        <div class="form-group">
                            <label for="edit_username">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_username" name="username" value="<?php echo $edit_user['username']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_email">电子邮箱 <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="edit_email" name="email" value="<?php echo $edit_user['email']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_password">密码 <small class="text-muted">(留空则不修改)</small></label>
                            <input type="password" class="form-control" id="edit_password" name="password">
                        </div>
                        <div class="form-group">
                            <label for="edit_role">角色 <span class="text-danger">*</span></label>
                            <select class="form-control" id="edit_role" name="role" required>
                                <option value="">请选择角色</option>
                                <option value="admin" <?php echo $edit_user['role'] == 'admin' ? 'selected' : ''; ?>>管理员</option>
                                <option value="doctor" <?php echo $edit_user['role'] == 'doctor' ? 'selected' : ''; ?>>医生</option>
                                <option value="patient" <?php echo $edit_user['role'] == 'patient' ? 'selected' : ''; ?>>患者</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="edit_user" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#editUserModal').modal('show');
        });
    </script>
    <?php endif; ?>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
    <script>
        // 表格排序函数
        function sortTable(n) {
            // 在客户端临时排序当前页的数据
            var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById("userTable");
            switching = true;
            dir = "asc";
            
            while (switching) {
                switching = false;
                rows = table.rows;
                
                for (i = 1; i < (rows.length - 1); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("TD")[n];
                    y = rows[i + 1].getElementsByTagName("TD")[n];
                    
                    if (dir == "asc") {
                        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    } else if (dir == "desc") {
                        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                
                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                    switchcount++;
                } else {
                    if (switchcount == 0 && dir == "asc") {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }
        
        // 表格搜索功能
        $(document).ready(function(){
            // 实时搜索（当前页过滤）
            $("#searchInput").on("keyup", function() {
                var value = $(this).val().toLowerCase();
                $("#userTable tbody tr").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
            
            // 搜索按钮点击事件（将来可以扩展为服务器端搜索）
            $("#searchButton").on("click", function() {
                var value = $("#searchInput").val().toLowerCase();
                $("#userTable tbody tr").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
            
            // 编辑模态框自动显示
            <?php if (isset($edit_user)): ?>
            $('#editUserModal').modal('show');
            <?php endif; ?>
        });
    </script>
</body>
</html> 